//
//  LoginViewController.m
//  AddressBook
//
//  Created by mac on 2017/8/25.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "LoginViewController.h"

#import "RegisterViewController.h"
#import "RetrievePassworkViewController.h"
#import "TabBarViewController.h"

@interface LoginViewController () <UITextFieldDelegate>

@property (nonatomic, strong) UIImageView *imageLogo;
@property (nonatomic, strong) UITextField *accountFireld;
@property (nonatomic, strong) UITextField *passworkField;
@property (nonatomic, strong) UIButton *loginBtn;
@property (nonatomic, strong) UIButton *retrieveBtn;
@property (nonatomic, strong) UIButton *registerBtn;
@property (nonatomic, strong) UIView *backView;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.imageLogo];
    [self.view addSubview:self.backView];
    
    // 键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
    
}

//方法里对键盘弹出和将要消失做处理
- (void)keyboardShow:(NSNotification*)notification{
    //NSLog(@"显示键盘:%@",notification);
    //NSLog(@"%@",notification.userInfo);
    NSValue *keyboardEndFrameValue = notification.userInfo[UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardEndFrame;
    [keyboardEndFrameValue getValue:&keyboardEndFrame];
    
    // 往上移动
    [UIView animateWithDuration:0.2 animations:^{
        // 改变高度
        self.backView.frame = CGRectMake(0,50, ScreenW, ScreenH-10);
        self.backView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.7];
        
    }];
}

- (void)keyboardHide:(NSNotification*)notification{
    
    //NSLog(@"键盘消失:%@",notification);
    [UIView animateWithDuration:0.2 animations:^{
        
        self.backView.frame = CGRectMake(0, CGRectGetMaxY(self.imageLogo.frame)+40*ScaleW, ScreenH, ScreenH - CGRectGetHeight(self.imageLogo.frame));
        self.backView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:1];
        
    }];
}


#pragma make - UITextFieldDelegater

-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    NSLog(@"%@",textField.text);
    if (textField.text.length < 11 && textField.text.length > 0 && textField == self.accountFireld) {
        [self alertShow:@"提示" message:@"请输入正确的手机号码"];
        //        [self showHint:CustomLocalizedString(@"请输入正确的手机号码", nil)];
        
    }else if (textField.text.length < 6 && textField.text.length > 8 &&textField == self.passworkField){
        [self alertShow:@"提示" message:@"密码要大于6位数小于8位数"];
    }
    
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (textField == self.accountFireld) {
        
        NSString * text  = [NSString stringWithFormat:@"%@%@",textField.text,string];
        if (text.length == 11) {
            //            self.accountFireld.text = [text substringToIndex:text.length-1];
            //NSLog(@"%@ len:%@",string,textField.text);
            NSString *regex = @"^((13[0-9])|(147)|(17[0,1][6,8])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
            NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
            BOOL isMatch = [pred evaluateWithObject:text];
            NSLog(@"is:%d",isMatch);
            if (isMatch == false) {
                //                [self showHint:CustomLocalizedString(@"请输入正确的手机号码", nil)];
                [self alertShow:@"提示" message:@"请输入正确的手机号码"];
            }
        }else if (textField.text.length >= 11){
            [self alertShow:@"提示" message:@"号码格式不正确"];
            //            [self showHint:CustomLocalizedString(@"号码格式不正确", nil)];
            
        }
        
    }
    return YES;
}



-(UIImageView *)imageLogo{
    if (!_imageLogo) {
        _imageLogo = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 120*ScaleW, 40*ScaleW)];
        _imageLogo.center = CGPointMake(ScreenW/2, 140);
        _imageLogo.image = [UIImage imageNamed:@"register_bg"];
        
    }
    return _imageLogo;
}

-(UIView *)backView{
    
    if (!_backView) {
        _backView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.imageLogo.frame)+40*ScaleW, ScreenH, ScreenH - CGRectGetHeight(self.imageLogo.frame))];
        UIImageView *image1 = [[UIImageView alloc]initWithFrame:CGRectMake(35*ScaleW, 5*ScaleW, ScreenW - (35*2*ScaleW), 42)];
        image1.image = [UIImage imageNamed:@"et_bg_login.9"];
        [_backView addSubview:image1];
        [_backView addSubview:self.accountFireld];
        UIImageView *image2 = [[UIImageView alloc]initWithFrame:CGRectMake(35*ScaleW, CGRectGetMaxY(image1.frame)+ 28, ScreenW - (35*2*ScaleW), 42)];
        image2.image = [UIImage imageNamed:@"et_bg_login.9"];
        [_backView addSubview:image2];
        [_backView addSubview:self.passworkField];
        [_backView addSubview:self.loginBtn];
        UILabel *line = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 1, 20)];
        line.backgroundColor = [UIColor grayColor];
        line.center = CGPointMake(ScreenW/2, self.loginBtn.frame.origin.y + 60);
        [_backView addSubview:line];
        self.retrieveBtn = [[UIButton  alloc]initWithFrame:CGRectMake(CGRectGetMinX(line.frame) - 80, CGRectGetMinY(line.frame), 80, 20)];
        [self.retrieveBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
        [self.retrieveBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        self.retrieveBtn.tag = 1111;
        self.retrieveBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [self.retrieveBtn setTitleColor:MainColor forState:UIControlStateNormal];
        [_backView addSubview:self.retrieveBtn];
        
        self.registerBtn = [[UIButton  alloc]initWithFrame:CGRectMake(CGRectGetMaxX(line.frame) , CGRectGetMinY(line.frame), 80, 20)];
        [self.registerBtn setTitle:@"用户注册" forState:UIControlStateNormal];
        [self.registerBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        self.registerBtn.tag = 1112;
        self.registerBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [self.registerBtn setTitleColor:MainColor forState:UIControlStateNormal];
        [_backView addSubview:self.registerBtn];
    }
    return _backView;
}

-(UITextField *)accountFireld{
    if (!_accountFireld) {
        _accountFireld = [[UITextField alloc]initWithFrame:CGRectMake(40*ScaleW, 5*ScaleW, ScreenW - (40*2*ScaleW), 40)];
//        _accountFireld.layer.borderWidth = 1;
//        _accountFireld.layer.masksToBounds = YES;
        _accountFireld.layer.borderColor = [UIColor grayColor].CGColor;
        _accountFireld.layer.shadowColor = [UIColor grayColor].CGColor;
//        _accountFireld.layer.shadowOffset = CGSizeMake(1.0, 1.0);
//        _accountFireld.layer.shadowOpacity = YES;
        _accountFireld.clearButtonMode = UITextFieldViewModeAlways;
        _accountFireld.placeholder = @"请输入账号";
        
        UIView * userLeft = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
        UIImageView * left = [[UIImageView alloc]initWithFrame:CGRectMake(0, 7.5, 25, 25)];
        left.image = [UIImage imageNamed:@"login_username_logo"];
        [userLeft addSubview:left];
        _accountFireld.leftViewMode = UITextFieldViewModeAlways;
        _accountFireld.leftView = userLeft;
        _accountFireld.text = @"18378164697";

    }
    return _accountFireld;
}

-(UITextField *)passworkField{
    if (!_passworkField) {
        _passworkField = [[UITextField alloc]initWithFrame:CGRectMake(40*ScaleW, CGRectGetMaxY(self.accountFireld.frame)+30, ScreenW - (40*2*ScaleW), 40)];
//        _passworkField.layer.borderWidth = 1;
        _passworkField.layer.borderColor = [UIColor grayColor].CGColor;
        _passworkField.layer.shadowColor = [UIColor grayColor].CGColor;
//        _passworkField.layer.shadowOffset = CGSizeMake(1.0, 1.0);
//        _passworkField.layer.shadowOpacity = YES;
        _passworkField.placeholder = @"请输入密码";
        _passworkField.clearButtonMode = UITextFieldViewModeAlways;
        _passworkField.secureTextEntry = YES;
        UIView * userLeft = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
        UIImageView * left = [[UIImageView alloc]initWithFrame:CGRectMake(0, 7.5, 25, 25)];
        left.image = [UIImage imageNamed:@"login_password_logo"];
        [userLeft addSubview:left];
        _passworkField.leftViewMode = UITextFieldViewModeAlways;
        _passworkField.leftView = userLeft;
        _passworkField.text = @"123456";
        
    }
    return _passworkField;
}

-(UIButton *)loginBtn{
    if (!_loginBtn) {
        _loginBtn = [[UIButton alloc]initWithFrame:CGRectMake(40*ScaleW, CGRectGetMaxY(self.passworkField.frame)+40, ScreenW - (40*2*ScaleW), 40)];
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        _loginBtn.backgroundColor = MainColor;
        _loginBtn.layer.cornerRadius = 2.0;
        _loginBtn.layer.masksToBounds = YES;
        [_loginBtn addTarget:self action:@selector(loginClick) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _loginBtn;
}


-(void)loginClick{
    if (self.accountFireld.text == nil || self.passworkField.text == nil) {
        [self alertShow:@"提示" message:@"账号或者密码不能为空"];
    }
    else if (self.accountFireld.text.length != 11) {
        [self alertShow:@"提示" message:@"请输入正确的电话号码"];
    }
    else{
        [self showHudInView:self.view hint:@"登录中"];
        NSString *url = [NSString stringWithFormat:@"%@%@",MAIN_URL,LOGIN_URL];
        NSDictionary *dic = @{@"member_phone":self.accountFireld.text ,@"member_pass":self.passworkField.text};
        [NetworkRequestManager postWithUrl:url parameter:dic success:^(id requestData) {
            
            // 最好建一个枚举
            NSInteger code = ((NSNumber *)requestData[@"code"]).integerValue;
            
            if (code == 10001 || code == 10000) {
                [self logInSucceed:requestData];
                
            }else if (code == 20000) {
                [self hideHud];
                [self showHint:@"登录失败"];
                
            }else{
                [self hideHud];
                [self showHint:@"登录失败"];
                
            }
            
        } failure:^(NSError *error) {
            [self hideHud];
            [self alertShow:@"提示" message:@"登录失败"];
            
        }];
    }
    
}

/** 登录成功 */
- (void)logInSucceed:(NSDictionary *)requestData {
    /** 转换成model */
    UserDataModel *model = [UserDataModel loginModelArrayJsonDic:requestData];
    /** 存储model到本地 */
    [UserDataModel saveModel:model];
    
    /** 最好UD建一个文件来管理, 然后里面的 key, 就放在一个header文件里 */
    /** 存储账号密码, 其实这里最好分开存, 一个账号, 一个密码, 取的方便 */
    [[NSUserDefaults standardUserDefaults] setObject:@{@"member_phone":self.accountFireld.text,@"member_pass":self.passworkField.text} forKey:KUSERPASSWORD];
    
    /** 记录登录成功 */
    [[NSUserDefaults standardUserDefaults] setObject:@"YES" forKey:LOGIN_SUCCESSFUL];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    /** 切换根视图, 最好还是不要这样切 */
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    window.rootViewController = [[TabBarViewController alloc] init];
}


-(void)btnClick:(UIButton *)sender{
    if (sender.tag == 1111) {
        RetrievePassworkViewController *retri = [[RetrievePassworkViewController alloc]init];
        [self presentViewController:retri animated:NO completion:nil];
    }else if (sender.tag == 1112){
        RegisterViewController *registerVC = [[RegisterViewController alloc]init];
        [self presentViewController:registerVC animated:NO completion:nil];
    }
}


-(void)alertShow:(NSString *)title message:(NSString *)message{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
    [self.accountFireld resignFirstResponder];
    [self.passworkField resignFirstResponder];
    
}

@end
